// 引入加密插件
const bcrypt = require('bcryptjs')
const qs = require('qs')

module.exports = {
  // 加密
  bcryptData(password) {
    // 生成盐
    const salt = bcrypt.genSaltSync(10)
    return bcrypt.hashSync(password, salt)
  },
  // 解密
  async comparePwd(password, user_password) {
    return await bcrypt.compare(password, user_password)
  },
  // token生成
  async generateToken(data) {
    const accessToken = await this.app.jwt.sign(data, this.app.config.jwt.secret, {
      expiresIn: this.app.config.jwt.expiresIn
    })
    const refreshToken = await this.app.jwt.sign(data, this.app.config.jwt.secret, {
      expiresIn: this.app.config.jwt.refreshExpiresIn
    })
    return {
      accessToken,
      refreshToken
    }
  },
  // 去除对象中的空值
  removeNull(obj) {
    Object.keys(obj).forEach(item => {
      if (!obj[item] && obj[item] !== false) delete obj[item]
    })
    return obj
  },
  // 获取文件后缀名
  getType(file) {
    const filename = file
    const index1 = filename.lastIndexOf('.')
    const index2 = filename.length
    const type = filename.substring(index1, index2)
    return type
  },
  // 发送curl请求
  curlPost(url, data) {
    const options = {
      method: 'POST',
      dataType: 'json',
      headers: {
        cookie: qs.stringify(this.app.config.moocCookie),
        'content-type': 'application/x-www-form-urlencoded'
      }
    }
    if (data) {
      options.data = data
    }
    return this.ctx.curl(url, options)
  },
  // 添加模糊字段
  addFuzzyField(fuzzyField, where) {
    where = this.removeNull(where)
    const { Op } = this.app.Sequelize
    Object.keys(fuzzyField).forEach(key => {
      if (fuzzyField[key]) {
        where[key] = {
          [Op.like]: '%' + (fuzzyField[key] || '') + '%'
        }
      }
    })
    return where
  }
}
